package com.tonghu.bluetoothregistration.bean;

import android.bluetooth.BluetoothDevice;

/**
 * Created by tonghu on 6/7/15.
 */
public class ScanData {
    public String name;
    public int major;
    public int minor;
    public String proximityUuid;
    public String bluetoothAddress;
    public int txPower;
    public int rssi;
    public double distance;


    public static ScanData fromScanData(BluetoothDevice device, int rssi,byte[] scanData) {

        int startByte = 2;
        boolean patternFound = false;
        int tmpRssi = 0;

        while (startByte <= 5) {
            if (((int)scanData[startByte+2] & 0xff) == 0x02 &&
                    ((int)scanData[startByte+3] & 0xff) == 0x15) {
                // yes!  This is an iBeacon
                patternFound = true;
                break;
            }
            else if (((int)scanData[startByte] & 0xff) == 0x2d &&
                    ((int)scanData[startByte+1] & 0xff) == 0x24 &&
                    ((int)scanData[startByte+2] & 0xff) == 0xbf &&
                    ((int)scanData[startByte+3] & 0xff) == 0x16) {
                ScanData iBeacon = new ScanData();
                iBeacon.major = 0;
                iBeacon.minor = 0;
                iBeacon.proximityUuid = "00000000-0000-0000-0000-000000000000";
                iBeacon.txPower = -74;
                return iBeacon;
            }
            else if (((int)scanData[startByte] & 0xff) == 0xad &&
                    ((int)scanData[startByte+1] & 0xff) == 0x77 &&
                    ((int)scanData[startByte+2] & 0xff) == 0x00 &&
                    ((int)scanData[startByte+3] & 0xff) == 0xc6) {

                ScanData iBeacon = new ScanData();
                iBeacon.major = 0;
                iBeacon.minor = 0;
                iBeacon.proximityUuid = "00000000-0000-0000-0000-000000000000";
                iBeacon.txPower = -74;
                return iBeacon;
            }
            startByte++;
        }

        if (patternFound == false) {
            // This is not an iBeacon
            return null;
        }

        ScanData iBeacon = new ScanData();

        iBeacon.major = (scanData[startByte+20] & 0xff) * 0x100 + (scanData[startByte+21] & 0xff);
        iBeacon.minor = (scanData[startByte+22] & 0xff) * 0x100 + (scanData[startByte+23] & 0xff);
        iBeacon.txPower = (int)scanData[startByte+24]; // this one is signed
//    	data = new IdRssiData(0, rssi);

//        kanmanFliterMap.put(iBeacon.major, data);

//        kalmanFilteringDoRssi(iBeacon.major, rssi);

        iBeacon.rssi = (int) rssi;

//		PedometerMediator pedometerMediator = PedometerMediator.getInstanceWithoutContext();
//		if (pedometerMediator != null) {
//			//step = pedometerMediator.getTotal();
//		}
//		step = Acceleration.Radians;

		/* 	AirLocate:
		  * 02 01 1a 1a ff 4c 00 02 15  # Apple's fixed iBeacon advertising prefix
		  * e2 c5 6d b5 df fb 48 d2 b0 60 d0 f5 a7 10 96 e0 # iBeacon profile uuid
		  * 00 00 # major
	  	  * 00 00 # minor
	   	  * c5 # The 2's complement of the calibrated Tx Power

		  * Estimote:
		  * 02 01 1a 11 07 2d 24 bf 16
		  * 394b31ba3f486415ab376e5c0f09457374696d6f7465426561636f6e
	     */

        byte[] proximityUuidBytes = new byte[16];
        System.arraycopy(scanData, startByte+4, proximityUuidBytes, 0, 16);
        String hexString = bytesToHexString(proximityUuidBytes);
        StringBuilder sb = new StringBuilder();
        sb.append(hexString.substring(0,8));
        sb.append("-");
        sb.append(hexString.substring(8,12));
        sb.append("-");
        sb.append(hexString.substring(12,16));
        sb.append("-");
        sb.append(hexString.substring(16,20));
        sb.append("-");
        sb.append(hexString.substring(20,32));
        iBeacon.proximityUuid = sb.toString();

        if(device != null)
        {
            iBeacon.bluetoothAddress = device.getAddress();
            iBeacon.name = device.getName();
        }


//        if(iBeacon.rssi < 0.0)
//        {
//            //已简单适配手机型号：三星note3 （-63dbm）、三星i9502（-60dbm）、三星note2（-74dbm）
//            if (iBeacon.rssi >= -95) {

//                if (!majorRssi1.containsKey(iBeacon.major)) {
//                    majorRssi1.put(iBeacon.major, new ArrayList<Integer>());
//                } else {
//                    majorRssi1.get(iBeacon.major).add(iBeacon.rssi);
//                }
//                //Log.e("kalmanLLL", " major" + iBeacon.major + "rssi" + iBeacon.rssi);
//                if (majorRssi1.get(iBeacon.major).size() >= 10) {
//
//                    nodeFlags = iBeacon.major;
//                    step = 0;
//                    locationData.dev_last_radius = 0.01;
//                    locationData.dev_last_theta = 0.0;
//                    locationData.new_radius = 0.01;
//                    locationData.new_theta = 0.0;
//                    locationData.step_distance_count = 0;
//                    Acceleration.clean();
//                    majorRssi1.get(iBeacon.major).clear();
//
////					if (!isPlaying) {
////						Log.i("kkkk", "111");
////						streamId = App.soundPool.play(App.soundId, 1, 1, 10, 100, 1);
////						isPlaying = true;
////						Log.i("kkkk", "start: " + streamId);
////					}
//
//                }
//            } else {
//                majorRssi1.get(iBeacon.major).clear();
////				if (isPlaying) {
////					App.soundPool.stop(streamId);
////					isPlaying = false;
////					Log.i("kkkk", "stop");
////				}
//            }
////			nodeFlags = 0;
            //将得到新的角度和相对位置
//			if(locationData.step_distance_count != step)
//			{
//				if(calcRelativePosition(locationData.dev_last_radius, locationData.dev_last_theta, (step - locationData.step_distance_count) * 0.60,  Orientation.get_pose()[0], position_info))
//				{
//					locationData.new_radius = position_info[0];
//					locationData.new_theta = position_info[1];
//					position_info[0] = 0.01;
//					position_info[1] = 0.0;
//					//Log.i("hewu11", "radius : " + position_info[0] + "  theta : " + position_info[1]);
//
//					locationData.dev_last_radius = locationData.new_radius;
//					locationData.dev_last_theta = locationData.new_theta;
//				}
//				locationData.step_distance_count = step;
//			}
//
//			radius = locationData.dev_last_radius;
//			theta = locationData.dev_last_theta;
//        }

        return iBeacon;
    }

    private static String bytesToHexString(byte[] src){
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}


